package com.jerome.election.storage;

/**
 * Simple circular linked list based on Lamport.
 */
public class RingBuffer {
    /**
     * The most recently consumed data point.
     */
    private int offset = 0;
    /**
     * The latest data point.
     */
    private int head = 0;
    /**
     * Size of the circular queue.
     */
    private int max;
    /**
     * Circular array.
     */
    private Object[] ring;

    public RingBuffer(int max) {
        this.max = max;
        ring = new Object[max];
    }

    /**
     * Add data to the circular head first.
     *
     * @param weatherVo
     */
    public synchronized void add(Object weatherVo) {
        ring[head] = weatherVo;
        head++;
        head = head % max;
        if (offset == head) {
            offset++;
            offset = offset % max;
        }
    }

    /**
     * Consume the next data point.
     */
    public synchronized Object offsetNext() {
        if (offset == head) {
            return null;
        }
        Object vo = ring[offset];
        offset++;
        offset = offset % max;
        return vo;
    }

    public int getOffset() {
        return offset;
    }

    public int getHead() {
        return head;
    }
}
